<?php
/*
	plugin.class
		插件处理类，目前不支持传入类处理
	#author: corrie
	#update: corrie
	#latest: 03/02/09
	#version: 1.2
*/

if(!defined('CORE')) {exit('Access Denied');}

class Plugin {
	//var $_hook;
	//var $_
	function Plugin(){
	}
	
	function setaction($tag, $function, $order=10, $num_args=1){
		global $hook;
		if(isset($hook[$tag][$order][$function])){
			return;
		}
		self::bindhook($tag, $function, $order, $num_args);
		return true;		
	}
	
	function setfilter($tag, $function, $order=10, $num_args=1){
	}
	
	function doaction($tag, $arg=''){
		global $hook, $addon;
		$args[] = $arg;
		for ( $a = 2; $a < func_num_args(); $a++ )
			$args[] = func_get_arg($a);
		foreach($addon[$tag] as $key=>$ado){
			foreach($ado as $k=>$a){
				@include PLUGIN_DIR.$a;
				if($hk = $hook[$tag][$key][$k]){
					call_user_func_array($hk['function'], array_slice($args, 0, (int) $hk['num_args']));
				}
			}
		}
	}
	
	function dofilter($tag, $function=false){
	}
	
	function existaction($tag, $function=false){
	}
	
	function existfilter($tag, $function=false){
	}
	
	function bindhook($tag, $function, $order, $num_args){
		global $hook, $current_addon;
		$hook[$tag][$order][$function] = array(
			'function' => $function,
			'num_args' => $num_args
		);
		$current_addon = self::getidfromhook($tag, $function, $order);		
	}
	
	function updateoption($plugin, $args){
	}
	
	function getidfromhook($tag, $function, $order){
		return "{$tag}__${order}__{$function}";
	}
	
	function gethookfromid($id){
		list($tag, $order, $function) = explode("__", $id);
		return $hook[$tag][(int)$order][$function];
	}
	
	function active($plugin){
		global $hook, $current_addon;
		if(is_array($plugin))return false;	//不提供单一入口的多插件激活
		include PLUGIN_DIR."setting.php";
		if(!file_exists(PLUGIN_DIR.$plugin))
			return false;					//错误条件：插件不存在
		include PLUGIN_DIR.$plugin;
		
		$addon_bak = $addon;
		
		if($current_addon){
			list($tag, $order, $function) = explode('__', $current_addon);
			if(!isset($addon[$tag][$order][$function]))
				$addon[$tag][$order][$function] = $plugin;					
		}
		//print_r($addon);
		if($addon_bak!=$addon){
			self::writesetting(PLUGIN_DIR."setting.php", self::arraydump($addon));
			return true;
		}
		return false;						//错误条件：插件已激活
	}
	
	function deactive($plugin){
		
	}
	
	function arraydump($arr){
		$str = "//->start\n\n";
		foreach($arr as $tag=>$ado){
			foreach($ado as $order=>$func){
				foreach($func as $function=>$a){
					$str.= "\$addon['{$tag}']['{$order}']['{$function}'] = '$a';\n";
				}
			}
		}
		$str.= "\n//<-end";
		return $str;
	}
	
	function writesetting($file, $content){
$t = "<?php
/*
* plugin setting file
* \t插件配置信息
* #update: corrie
* #version: 1.2
*/\n
if(!defined('CORE')) {exit('Access Denied');}\n";
		$t.= $content;
		$t.= "\n?>";
		file_put_contents($file, $t);
		return true;
	}
	
}
$hook = array();
$current_addon = "";
?>